package net.gxf.check;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.gxf.common.etf.ETF;
import net.gxf.common.etf.ETFTool;
import net.gxf.common.etf.StockETF;
import net.gxf.common.etf.StockPause;
import net.gxf.common.util.ExportFileUtil;

/**
 * 上证所停复牌股票查询，实现方式为解析网页：
 * http://www.sse.com.cn/sseportal/webapp/datapresent/querytradetipsnew 中的停复牌股票
 * 
 * @author maybe
 * 
 */
public class SH_PaseStockAnalysis {
	int i = 0;
	private String startFlag = "停(复)牌原因";
	private Map<String, StockPause> pauseMap = new HashMap<String, StockPause>();// 存储停牌股票

	public void run() {
		try {
			//startFlag=	new String("\u505c(\u590d)\u724c\u539f\u56e0".getBytes("GBK"));
			//startFlag=	new String("停(复)牌原因".getBytes("GBK"),"UTF-8");
			URL url = new URL("http://www.sse.com.cn/sseportal/webapp/datapresent/querytradetipsnew");
			URLConnection conn = url.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"GBK"));
			String line = null;

			// 定位到开始
			while ((line = reader.readLine()) != null) {
				if (line.length() == 0)
					continue;
				if (line.contains(startFlag)) {// 找到目标
					System.out.println("\u505c(\u590d)\u724c\u539f\u56e0");
					System.out.println(line);
					reader.readLine();// skip
					break;
				}
			}
			deal(reader);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/** 开始处理 */
	private void deal(BufferedReader reader) {
		try {
			String reString = reader.readLine();
			while (reString != null && !reString.toLowerCase().contains("</table>")) {// </table>为结束标志
				if (!reString.toLowerCase().contains("height")) {
					reString = reader.readLine();
					continue;
				}
				dealBlock(reader);
				reString = reader.readLine();// skip end block

			}
			System.out.println("ddd");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * <tr bgcolor="#F4F4F4" height="20">
	 * <td class="table3" bgcolor="white" nowrap>600800</td>
	 * <td class="table3" bgcolor="white" nowrap>天津磁卡</td>
	 * <td class="table3" bgcolor="white" nowrap>2012-10-17</td>
	 * <td class="table3" bgcolor="white" nowrap>9:30-10:30</td>
	 * <td class="table3" bgcolor="white" nowrap>刊登股票交易异常波动公告</td>
	 * </tr>
	 * 解析一小块 analysis a block
	 * 
	 * @param reader
	 * @throws IOException
	 */
	private void dealBlock(BufferedReader reader) throws IOException {
		// 证券代码
		String codeString = reader.readLine();
		int start = codeString.indexOf(">");
		int end = codeString.indexOf("<", start);
		String code = codeString.substring(start + 1, end).trim();

		// 证券简称
		String nameString = reader.readLine();
		start = nameString.indexOf(">");
		end = nameString.indexOf("<", start);
		String name = nameString.substring(start + 1, end).trim();

		// 停(复)牌时间
		String timeString = reader.readLine();
		start = timeString.indexOf(">");
		end = timeString.indexOf("<", start);
		String time = timeString.substring(start + 1, end).trim();

		// 停牌期限
		String deadlineString = reader.readLine();
		start = deadlineString.indexOf(">");
		end = deadlineString.indexOf("<", start);
		String deadline = 	deadlineString.substring(start + 1, end).trim();
	

		// 停牌原因
		String reasonString = reader.readLine();
		start = reasonString.indexOf(">");
		end = reasonString.indexOf("<", start);
		String reason =	reasonString.substring(start + 1, end).trim();

		reader.readLine();

		StockPause stockPause = new StockPause();
		stockPause.setCode(code);
		stockPause.setName(name);
		stockPause.setTime(time);
		stockPause.setDeadline(deadline);
		stockPause.setReason(reason);

		pauseMap.put(code, stockPause);
		// System.out.println(stockPause.getCode() + "    " +
		// stockPause.getName());
	}

	protected void result() {
		boolean hasPause = false;
		Map<String, ETF> etFs = ETFTool.getETFs();
		StringBuffer document = new StringBuffer();
		document.append("******含停牌股的ETF详细信息********\r\n");
		for (ETF etf : etFs.values()) {
			List<StockPause> pauseStocks = new ArrayList<StockPause>();
			List<StockETF> stockList = etf.getStockList();
			for (StockETF stockETF : stockList) {
				if (pauseMap.containsKey(stockETF.getCode())) {
					pauseStocks.add(pauseMap.get(stockETF.getCode()));
				}
			}
			if (pauseStocks.size() > 0) {
				hasPause = true;
				document.append("***************************\r\n");
				document.append("一级市场代码：").append(etf.getFundid1()).append("\r\n");
				document.append("代码\t名称\t\t停牌期限\t\t\t\t停(复)牌原因\r\n");
				for (StockPause stockPause : pauseStocks) {
					document.append(stockPause.getCode()).append("\t").append(stockPause.getName()).append("\t\t").append(stockPause.getDeadline().trim()).append("\t\t")
							.append(stockPause.getReason().trim()).append("\r\n");
				}
				document.append("***************************\r\n");
				pauseStocks.clear();
			}
		}
		if (!hasPause)
			document.append("\r\n50ETF,180ETF,300ETF中没有含有停复牌股票\r\n\r\n");
		document.append("******************************\r\n");

		System.out.println(document.toString());
		ExportFileUtil.ExportTxt("C:/ETF/pause.txt", document.toString().getBytes());
	}

	public static void main(String[] args) {
		SH_PaseStockAnalysis paseInfoAnalysis = new SH_PaseStockAnalysis();
		paseInfoAnalysis.run();
		paseInfoAnalysis.result();
	}
}
